<template>
  <div>
    <div class="task-component" v-for="(task, i) in taskGroup" :key="i">
      <el-card>
        <!-- 配置组标题 -->
        <div class="set-title-contain">
          <div class="set-title-contain-name">
            <svg-icon
              icon-class="setGroup"
              style="font-size: 18px; padding-right: 5px"
            ></svg-icon
            >{{ task.name }}
          </div>
          <div>
            <span style="padding-right: 5px">{{
              task.disable == true ? "已开启" : "已禁用"
            }}</span>
            <el-switch
              active-color="#02439e"
              v-model="task.disable"
              @click="handlerSwitch(task)"
            ></el-switch>
          </div>
        </div>
        <!-- 选择星期 -->
        <div class="set-day-contain">
          <div
            v-for="(item, index) in DayList"
            :key="index"
            class="day-item"
            :class="getDayClass(item.id, i)"
            @click="handlerClickDay(item, i)"
          >
            {{ item.day }}
          </div>
        </div>
        <div class="set-title-contain-num">
          时间段配置({{ task.scheList.length }}/8)
        </div>
        <!-- 时间段配置 -->
        <div v-for="(time, index) in task.scheList" :key="index">
          <div class="set-timeSet-contain">
            <div class="set-timeSet-contain-set">
              <div class="set-timeSet-contain-set-item">
                <el-time-picker
                  v-model="time.showTime"
                  value-format="HH:mm"
                  format="HH:mm"
                  arrow-control
                >
                </el-time-picker>
              </div>
              <div class="set-timeSet-contain-set-item">
                <el-select v-model="time.onOff" placeholder="请选择">
                  <el-option
                    v-for="item in selectFlagList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                  >
                  </el-option>
                </el-select>
              </div>
              <div
                class="set-timeSet-contain-set-item"
                v-if="time.onOff == '开机'"
              >
                <el-select v-model="time.fan" placeholder="请选择">
                  <el-option
                    v-for="item in selectSpeedList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </div>
              <div
                class="set-timeSet-contain-set-item"
                v-if="time.onOff == '开机'"
              >
                <el-input-number
                  placeholder="温度"
                  v-model="time.tempset"
                  controls-position="right"
                ></el-input-number>
              </div>
            </div>
            <div class="set-timeSet-contain-del">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="handlerDelItem(i, index)"
              ></el-button>
            </div>
          </div>
        </div>
        <!-- 配置组操作按钮 -->
        <div style="margin-top: 15px">
          <el-button
            class="btn-add"
            plain
            size="small"
            @click="handlerAddItem(i)"
            >添加时间段+</el-button
          >
          <el-button
            type="danger"
            plain
            size="small"
            @click="handlerDelGroup(i)"
            >删除本组</el-button
          >
        </div>
      </el-card>
    </div>
    <div class="add-group-btn" @click="handlerAddGroup">
      添加配置组<i class="el-icon-plus"></i>
    </div>
    <div class="set-save" @click="handlerSubmit">保存</div>
  </div>
</template>
<script>
export default {
  name: "DeviceDetailComponent",
  data() {
    return {
      DayList: [
        {
          day: "周日",
          id: "64",
          disabled: false,
          cIndex: null,
        },
        {
          day: "周一",
          id: "1",
          disabled: false,
          cIndex: null,
        },
        {
          day: "周二",
          id: "2",
          disabled: false,
          cIndex: null,
        },
        {
          day: "周三",
          id: "4",
          disabled: false,
          cIndex: null,
        },
        {
          day: "周四",
          id: "8",
          disabled: false,
          cIndex: null,
        },
        {
          day: "周五",
          id: "16",
          disabled: false,
          cIndex: null,
        },
        {
          day: "周六",
          id: "32",
          disabled: false,
          cIndex: null,
        },
      ],
      taskGroup: [
        {
          disable: false,
          id: 5432,
          isAsc: null,
          name: "配置组一",
          orderByColumn: null,
          pageNum: null,
          pageSize: null,
          params: {},
          remark: "[64, 1]",
          scheList: [
            {
              createBy: "鑫源管理员",
              createTime: "2025-10-13 13:03:07",
              day: "127",
              devId: 728,
              deviceNo: "DN4G359G0004",
              fan: 1,
              groupId: 236,
              id: 533,
              isAsc: null,
              onOff: 0,
              orderByColumn: null,
              pageNum: null,
              pageSize: null,
              params: {},
              remark: null,
              searchValue: null,
              tempset: "5",
              time: "0",
              updateBy: "",
              updateTime: null,
            },
            {
              createBy: "鑫源管理员",
              createTime: "2025-10-13 13:03:07",
              day: "127",
              devId: 728,
              deviceNo: "DN4G359G0004",
              fan: 0,
              groupId: 236,
              id: 533,
              isAsc: null,
              onOff: 1,
              orderByColumn: null,
              pageNum: null,
              pageSize: null,
              params: {},
              remark: null,
              searchValue: null,
              tempset: "5",
              time: "420",
              updateBy: "",
              updateTime: null,
            },
          ],
        },
        {
          disable: true,
          id: 5432,
          isAsc: null,
          name: "配置组二",
          orderByColumn: null,
          pageNum: null,
          pageSize: null,
          params: {},
          remark: "[2, 4]",
          scheList: [
            {
              createBy: "鑫源管理员",
              createTime: "2025-10-13 13:03:07",
              day: "127",
              devId: 728,
              deviceNo: "DN4G359G0004",
              fan: null,
              groupId: 236,
              id: 533,
              isAsc: null,
              onOff: null,
              orderByColumn: null,
              pageNum: null,
              pageSize: null,
              params: {},
              remark: null,
              searchValue: null,
              tempset: "5",
              time: "0",
              updateBy: "",
              updateTime: null,
            },
            {
              createBy: "鑫源管理员",
              createTime: "2025-10-13 13:03:07",
              day: "127",
              devId: 728,
              deviceNo: "DN4G359G0004",
              fan: null,
              groupId: 236,
              id: 533,
              isAsc: null,
              onOff: null,
              orderByColumn: null,
              pageNum: null,
              pageSize: null,
              params: {},
              remark: null,
              searchValue: null,
              tempset: "5",
              time: "420",
              updateBy: "",
              updateTime: null,
            },
          ],
        },
      ],
      tempSelectedDays: [],
      selectFlagList: [
        {
          dictLabel: "开机",
          dictValue: "1",
          dictCode: 37,
          dictSort: 1,
        },
        {
          dictLabel: "关机",
          dictValue: "0",
          dictCode: 38,
          dictSort: 2,
        },
      ],
      selectSpeedList: [
        {
          dictLabel: "自动",
          dictValue: "0",
          dictCode: 0,
          dictSort: 0,
        },
        {
          dictLabel: "低速",
          dictValue: "1",
          dictCode: 1,
          dictSort: 1,
        },
        {
          dictLabel: "中速",
          dictValue: "2",
          dictCode: 2,
          dictSort: 2,
        },
        {
          dictLabel: "高速",
          dictValue: "3",
          dictCode: 3,
          dictSort: 3,
        },
      ],
    };
  },
  created() {
    this.initTaskGroup();
  },
  methods: {
    initTaskGroup() {
      this.taskGroup.forEach((item, groupIndex) => {
        if (item.scheList && item.scheList.length) {
          item.remarks = JSON.parse(item.remark); // 将字段换转化成数组
          item.disabled = JSON.parse(item.disable); // 将字符串转化成布尔值

          //为配置组添加独立的触发控件
          item.scheList.forEach((timeItem) => {
            timeItem.onOff = timeItem.onOff == 1 ? "开机" : "关机";
            this.$set(timeItem, "onOff", timeItem.onOff);
            this.$set(timeItem, "showTime", this.minutesToTime(timeItem.time));
          });
        }
        // 初始化 tempSelectedDays，将当前配置组选中的日期放入
        if (item.remark) {
          try {
            // 解析 remark 字段，获取已选中的日期
            const selectedDays = JSON.parse(item.remark);
            if (Array.isArray(selectedDays)) {
              // 将选中的日期ID转换为字符串并存储到 tempSelectedDays 中
              this.tempSelectedDays[groupIndex] = selectedDays.map((day) =>
                day.toString()
              );
            }
          } catch (e) {
            console.warn("Failed to parse remark for group:", groupIndex, e);
          }
        }
      });
    },
    // 提交保存
    handlerSubmit() {
      //整理提交数据
      let result = [];
      for (var i = 0; i < this.taskGroup.length; i++) {
        let selectedDays = [];
        // 检查配置组内时间段是否有重复
        const timeSet = new Set();
        const duplicateTimes = [];
        for (var j = 0; j < this.taskGroup[i].scheList.length; j++) {
          const timeValue = this.taskGroup[i].scheList[j].showTime;
          if (timeSet.has(timeValue)) {
            duplicateTimes.push(timeValue);
          } else {
            timeSet.add(timeValue);
          }

          // 	// 仅在开机状态下检查温度是否为空
          if (this.taskGroup[i].scheList[j].onOff === "开机") {
            // 开机状态
            if (
              this.taskGroup[i].scheList[j].tempset === null ||
              this.taskGroup[i].scheList[j].tempset === undefined ||
              this.taskGroup[i].scheList[j].tempset === ""
            ) {
              this.$message({
                message: `"${this.taskGroup[i].name}"中存在温度未设置的时间段`,
                type: "warning",
              });
              return;
            }
            // 		if (taskGroup[i].scheList[j].fan === null ||
            // 			taskGroup[i].scheList[j].fan === undefined ||
            // 			taskGroup[i].scheList[j].fan === '') {
            // 			uni.showToast({
            // 				title: `"${taskGroup[i].name}"中存在风速未设置的时间段`,
            // 				icon: "none"
            // 			});
            // 			return;
            // 		}
          }
        }

        // 如果有重复时间段，提示用户
        if (duplicateTimes.length > 0) {
          this.$message({
            message: `配置组"${
              this.taskGroup[i].name
            }"中存在重复时间段: ${duplicateTimes.join(", ")}`,
            type: "warning",
          });
          return;
        }
        if (!this.tempSelectedDays[i] || !this.tempSelectedDays[i].length) {
          this.$message({
            message: "请为所有配置组选择日期",
            type: "warning",
          });
          return;
        }
        let data = {
          name: this.taskGroup[i].name,
          disabled: JSON.parse(this.taskGroup[i].disable),
          selectedDays: this.tempSelectedDays[i],
          timeSlots: [],
        };
        let ddd = 0;
        for (var k = 0; k < selectedDays.length; k++) {
          ddd += parseInt(selectedDays[k]);
        }
        //处理时间段
        for (var j = 0; j < this.taskGroup[i].scheList.length; j++) {
          let init = {
            Time: this.timeToMinutes(this.taskGroup[i].scheList[j].showTime),
            OnOff: this.taskGroup[i].scheList[j].onOff == "开机" ? 1 : 0,
            Fan: Number(this.taskGroup[i].scheList[j].fan),
            Tempset: Number(this.taskGroup[i].scheList[j].tempset),
            //特殊 上级数组相加
            Day: ddd,
          };
          data.timeSlots.push(init);
        }
        result.push(data);
      }
      console.log(result, "result");
    },
    // 添加时间段
    handlerAddItem(taskIndex) {
      if (this.taskGroup[taskIndex].scheList.length < 8) {
        let init = {
          id: null,
          day: null,
          time: "0", // 时间换算成一天内的分钟数的数值
          onOff: "开机", // 开机1；关机0
          fan: null, //风速根据字典取值
          tempset: undefined, //目标温度
          groupId: null,
          showTime: "00:00",
          disable: true,
        };
        this.taskGroup[taskIndex].scheList.push(init);
      } else {
        this.$message({
          message: "最多只能添加8个时间段",
          type: "warning",
        });
      }
    },
    // 添加配置组
    handlerAddGroup() {
      // 检查现有的配置组是否都已经选择了日期
      for (let i = 0; i < this.taskGroup.length; i++) {
        if (
          !this.tempSelectedDays[i] ||
          this.tempSelectedDays[i].length === 0
        ) {
          this.$message({
            message: `请先为"${this.taskGroup[i].name}"选择日期`,
            type: "warning",
          });
          return;
        }
      }

      // 检查是否还有未被任何配置组选择的日期
      const allDays = this.DayList.map((day) => day.id.toString());
      const selectedDaysSet = new Set();

      // 收集所有已被选择的日期
      Object.keys(this.tempSelectedDays).forEach((groupIndex) => {
        if (this.tempSelectedDays[groupIndex]) {
          this.tempSelectedDays[groupIndex].forEach((dayId) => {
            selectedDaysSet.add(dayId);
          });
        }
      });

      // 检查是否还有未选择的日期
      const hasUnselectedDays = allDays.some(
        (dayId) => !selectedDaysSet.has(dayId)
      );

      if (!hasUnselectedDays) {
        this.$message({
          message: "所有日期都已被其他配置组选择，无法添加新的配置组",
          type: "warning",
        });
        return;
      }
      let init = {
        remark: "[]",
        remarks: [],
        id: null,
        name: this.getNewGroupName(),
        disable: true,
        scheList: [
          {
            id: null,
            day: null,
            time: "0", // 时间换算成一天内的分钟数的数值
            onOff: "开机", // 开机1；关机0
            fan: null, //风速根据字典取值
            tempset: null, //目标温度
            groupId: null,
            showTime: "00:00",
          },
        ],
      };
      this.taskGroup.push(init);
    },

    // 选择开关机状态
    handlerSelectFlag(e) {},
    // 为新的配置组命名
    getNewGroupName() {
      // 提取当前所有配置组的序号（支持一到二十的中文数字）
      const usedNumbers = this.taskGroup
        .map((item) => {
          // 修改正则表达式以支持复合中文数字
          const match = item.name.match(
            /配置组([一二三四五六七八九十]+)(?![一二三四五六七八九十])/
          );
          if (match) {
            // 将中文数字转换为阿拉伯数字
            const chineseToNumber = {
              一: 1,
              二: 2,
              三: 3,
              四: 4,
              五: 5,
              六: 6,
              七: 7,
              八: 8,
              九: 9,
              十: 10,
              十一: 11,
              十二: 12,
              十三: 13,
              十四: 14,
              十五: 15,
              十六: 16,
              十七: 17,
              十八: 18,
              十九: 19,
              二十: 20,
            };
            return chineseToNumber[match[1]] || 0;
          }
          return 0;
        })
        .filter((num) => num > 0)
        .sort((a, b) => a - b);

      // 如果没有已使用的序号，直接返回"一"
      if (usedNumbers.length === 0) {
        return `配置组一`;
      }

      // 查找第一个缺失的序号
      let newNameNumber = 1;
      for (let i = 0; i < usedNumbers.length; i++) {
        if (usedNumbers[i] === newNameNumber) {
          newNameNumber++;
        } else if (usedNumbers[i] > newNameNumber) {
          // 找到了缺失的序号
          break;
        }
      }

      // 限制最多20个配置组
      if (newNameNumber > 20) {
        newNameNumber = 20;
      }

      // 将阿拉伯数字转换为中文大写
      const numberToChinese = (num) => {
        const chineseNumbers = {
          1: "一",
          2: "二",
          3: "三",
          4: "四",
          5: "五",
          6: "六",
          7: "七",
          8: "八",
          9: "九",
          10: "十",
          11: "十一",
          12: "十二",
          13: "十三",
          14: "十四",
          15: "十五",
          16: "十六",
          17: "十七",
          18: "十八",
          19: "十九",
          20: "二十",
        };
        return chineseNumbers[num] || "一";
      };

      return `配置组${numberToChinese(newNameNumber)}`;
    },
    // 删除时间段
    handlerDelItem(taskIndex, timeIndex) {
      this.taskGroup[taskIndex].scheList.splice(timeIndex, 1);
    },
    // 删除配置组
    handlerDelGroup(taskIndex) {
      this.taskGroup.splice(taskIndex, 1);
    },
    // 配置组开启关闭设置
    handlerSwitch(task) {
      task.disabled = !task.disabled;
    },
    // 点击选中日期
    handlerClickDay(data, groupIndex) {
      // 检查是否被禁用
      const disabledDays = this.getDisabledDays(groupIndex);
      if (disabledDays.has(data.id.toString())) {
        // 如果日期已被禁用，不执行任何操作
        return;
      }

      // 初始化 tempSelectedDays 数组（如果不存在）
      if (!this.tempSelectedDays[groupIndex]) {
        this.tempSelectedDays[groupIndex] = [];
      }

      const dayId = data.id.toString();
      const tempDays = this.tempSelectedDays[groupIndex];
      const selectedIndex = tempDays.indexOf(dayId);
      // 切换选中状态：如果已选中则移除，未选中则添加
      if (selectedIndex > -1) {
        // 如果已在 tempSelectedDays 中，则移除（取消选中）
        tempDays.splice(selectedIndex, 1);
      } else {
        // 如果不在 tempSelectedDays 中，则添加（设为选中）
        tempDays.push(dayId);
      }
      // 强制触发 Vue 响应式更新
      this.$set(this.tempSelectedDays, groupIndex, [...tempDays]);

      // 更新 remark 字段为 JSON 字符串格式
      // this.taskGroup[groupIndex].remarks = JSON.stringify(tempDays);
    },
    // 获取星期的class名
    getDayClass(dayId, groupIndex) {
      let classes = "";
      if (
        this.tempSelectedDays[groupIndex] &&
        this.tempSelectedDays[groupIndex].includes(dayId.toString())
      ) {
        classes += "dayTrue";
      }

      // 检查是否被禁用
      const disabledDays = this.getDisabledDays(groupIndex);
      if (disabledDays.has(dayId.toString())) {
        classes += " dayDisabled";
      }
      const result = classes.trim();
      return result;
    },
    // 获取已被其他配置组选中的日期
    getDisabledDays(currentGroupIndex) {
      const disabledDays = new Set();

      Object.keys(this.tempSelectedDays).forEach((groupIndex) => {
        if (
          parseInt(groupIndex) !== currentGroupIndex &&
          this.tempSelectedDays[groupIndex]
        ) {
          this.tempSelectedDays[groupIndex].forEach((dayId) => {
            disabledDays.add(dayId);
          });
        }
      });

      return disabledDays;
    },
    // 分钟转换为时间
    minutesToTime(totalMinutes) {
      if (!totalMinutes) {
        return "00:00";
      }
      const hours = Math.floor(totalMinutes / 60);
      const minutes = totalMinutes % 60;
      // 补零处理确保两位数格式
      return `${hours.toString().padStart(2, "0")}:${minutes
        .toString()
        .padStart(2, "0")}`;
    },
    // 时间转为分钟
    timeToMinutes(timeStr) {
      const [hours, minutes] = timeStr.split(":").map(Number);
      return hours * 60 + minutes;
    },
  },
};
</script>
<style lang="scss" scoped>
// 标题
.set-title-contain {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  .set-title-contain-name {
    font-weight: 600;
  }
}

// 星期
.set-day-contain {
  display: flex;
  .day-item {
    padding: 4px 12px;
    border-radius: 5px;
    margin-right: 5px;
    background: #e0e0e0;
    color: #000;
    border: 1px solid transparent;
    cursor: pointer;
  }
  .dayTrue {
    background-color: #165eff;
    color: #fff;
    border: 1px solid transparent;
  }
  .dayDisabled {
    background: #e0e0e0;
    color: #999;
    cursor: not-allowed;
    border: 1px solid transparent;
  }
}

// 时配置数量显示
.set-title-contain-num {
  color: 999;
  line-height: 40px;
}

// 时间段配置区域
.set-timeSet-contain {
  background-color: #f1f1f1;
  margin-bottom: 6px;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 7px 10px;
  .set-timeSet-contain-set {
    display: flex;
    align-items: center;
    .set-timeSet-contain-set-item {
      width: 150px;
      margin-right: 10px;
      .el-input {
        width: 100% !important;
      }
    }
  }
}
.el-card {
  margin-bottom: 10px;
}
// 添加时间段按钮
.btn-add {
  border: 1px solid #02439e;
  color: #02439e;
}
.btn-add:hover {
  background-color: #02439e;
  color: #fff;
}
// 添加配置组
.add-group-btn {
  width: 250px;
  margin: 20px auto;
  text-align: center;
  padding: 10px;
  border-radius: 20px;
  color: #fff;
  background: #02439e;
  cursor: pointer;
}

.set-save {
  position: absolute;
  bottom: 50px;
  right: 100px;

  z-index: 1000;
  /* 按钮基本样式 */
  padding: 10px 24px;
  border-radius: 9999px; /* 圆形边框 */
  border: none;

  /* 按钮背景渐变 */
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);

  /* 按钮文字样式 */
  color: white;
  font-size: 16px;
  font-weight: 500;
  text-align: center;

  /* 按钮发光效果 */
  box-shadow: 0 0 15px rgba(59, 130, 246, 0.7);

  /* 按钮交互效果 */
  transition: all 0.2s ease;
  cursor: pointer;
}
.set-save:hover {
  /* 悬停状态 */
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  box-shadow: 0 0 20px rgba(59, 130, 246, 0.9);
  transform: translateY(-2px);
}
</style>
